package seiacpjava_a2.datastructures.linkedlist;

import seiacpjava_a2.datastructures.DataStructure;

public class LinkedList extends DataStructure {

	private ListNode first;
	private ListNode last;
	private int length;

	public LinkedList() {
		first = null;
		last = null;
		this.length = 0;
	}

	public boolean isEmpty() {
		return first == null;
	}

	public void add(int item) {

		ListNode listNode = new ListNode(item);

		if (this.isEmpty()) {
			first = listNode;
			last = listNode;
			this.length++;
		} else {
			last.setNextNode(listNode);
			last = listNode;
			this.length++;
		}

	}

	public boolean contains(int item) {
		this.numberOfAccesses = 0;

		boolean isFound = false;

		if (!this.isEmpty()) {

			ListNode node = first;
			do {
				++(this.numberOfAccesses);
				if (node.getItem() == item) {
					isFound = true;
					break;
				} else {
					node = node.getNextNode();
				}
			} while (node != null);
		}

		return isFound;
	}

	public int getLength() {
		return length;
	}

	public void setLength(int length) {
		this.length = length;
	}

	public ListNode getFirst() {
		return first;
	}

	public ListNode getLast() {
		return last;
	}

	@Override
	public String getDatatStructureName() {
		return "LinkedList";
	}

	public int getItemAt(int index) {
		int internalIndex =0;
		if (index == 0) {
			return first.getItem();
		} else {

			ListNode node = first.getNextNode();
			internalIndex++;
			while (node != null) {
				if ( index == internalIndex)
				{
					return node.getItem();
				}
				else
				{
					node = node.getNextNode();
					internalIndex++;
				}
			}

		}
		
		return -1;
	}
}
